from pmapi import log
from pmapi import lock
from pmapi import utils
import sqlite3
import os
import sys


def search(keywords: str, fullshow=False, maxshow=20) -> list:
    lockn = lock.Lock("search")
    log.info("search packages")
    # 解析特殊语法
    keywordn = ""
    otherkey_list = []
    pkgname = ""
    offline = False

    for i in keywords.split(" "):
        if len(i) <= 1:
            continue
        if i[0] == "@":
            key_tuple = i[1:].split("=")
            if key_tuple[0] == "local":
                offline = True
                continue
            if len(key_tuple) <= 1:
                log.warn(f"magic key \"{key_tuple[0]}\" lose value, igrone")
                continue
            keys, vals = key_tuple
            if vals == "":
                log.warn("magic key " +
                         f"\"{key_tuple[0]}\" value is empty, igrone")
                continue
            if keys == "pkgname":
                pkgname = vals
            elif keys == "keyword":
                keywordn = vals
            else:
                log.warn("magic key " +
                         f"\"{key_tuple[0]}\" value is empty, igrone")
        else:
            otherkey_list.append(i)
    if offline:
        PACKAGE_PATH = f"{utils.find_disk()}\\" + \
            "PEinjector\\package".replace('\\', os.sep)
        pkg_list = os.listdir(PACKAGE_PATH)

    # 去重字典（有序）
    pkgdicts = {}

    # 查找包名
    db_path = utils.get_builtin_dir("database")  # 获取数据库目录
    conn = sqlite3.connect(db_path+"/"+'database.db')
    cursor = conn.cursor()
    if pkgname == "":
        if len(otherkey_list) > 0 != "":
            query = "SELECT * FROM sources WHERE name LIKE ?"
            params = ['%' + keyword + '%' for keyword in otherkey_list]
            # 将所有关键词组合成一个大的查询语句
            for i in range(1, len(otherkey_list)):
                query += " OR name LIKE ?"
            cursor.execute(query, params)
            results_p = cursor.fetchall()
        else:
            results_p = []
    else:
        query = "SELECT * FROM sources WHERE name LIKE ?"
        cursor.execute(query, ("%"+pkgname+"%",))
        results_p = cursor.fetchall()
    for i in results_p:
        if offline == True and i[0] not in pkg_list:
            continue
        pkgdicts[i[0]] = i
    # 查找标签
    if keywordn != "":
        # 合并查找语句 thank for chatglm
        query = "SELECT * FROM sources WHERE keywords LIKE ?"
        cursor.execute(query, ("%"+keywordn+"%",))
        results_k = cursor.fetchall()
        for i in results_k:
            if offline == True and i[0] not in pkg_list:
                continue
            pkgdicts[i[0]] = i
    # 查找描述
    # 合并查找语句 thank for chatglm
    query = "SELECT * FROM sources WHERE description LIKE ?"
    if len(otherkey_list) > 0:
        params = ['%' + keyword + '%' for keyword in otherkey_list]
        # 将所有关键词组合成一个大的查询语句
        for i in range(1, len(otherkey_list)):
            query += " OR description LIKE ?"
        cursor.execute(query, params)
        results_d = cursor.fetchall()
        for i in results_d:
            if offline == True and i[0] not in pkg_list:
                continue
            pkgdicts[i[0]] = i

    pkg_list_clean = list(pkgdicts.values())  # 去重后列表
    show_tag_name = 3
    tag_special = {
        "PEinjector": "\033[34m<core>\033[0m",
        "offical": "\033[34m<offical>\033[0m",
        "bot": "\033[32m(bot)\033[0m",
        "CI": "\033[32m(CI/CD)\033[0m",
        "remove": "\033[31m*\033[0m\033[41mREMOVE\033[0m\033[31m*\033[0m",
    }
    if len(pkg_list_clean) == 1:  # 只有一个软件包
        show_tag_name = 10  # 显示全部tag
    much_pkg_list = 0
    if len(pkg_list_clean) > maxshow:  # 截断输出
        much_pkg_list = len(pkg_list_clean)-maxshow
        pkg_list_clean = pkg_list_clean[:maxshow]
    if len(pkg_list_clean) <= 6 or fullshow:  # 长输出
        templetes = """{pkg_name}   {tags}
    {description}
Author:  {author}
Link:    {repo}
"""
    else:  # 短输出
        templetes = "{pkg_name}\t{tags}\t{description}"
        show_tag_name = 2

    # 遍历输出
    for i in pkg_list_clean:
        taglist = i[3].split(",")
        if taglist[-1] == "":
            taglist = taglist[:-1]
        much_tag_flag = 0
        if len(taglist) > show_tag_name:
            much_tag_flag = len(taglist)-show_tag_name
            taglist = taglist[:show_tag_name]
        tagshowtext = " ".join([(tag_special[j]
                                 if (j in tag_special)
                                 else "["+j+"]"
                                 )
                                for j in taglist])  # 生成标签行
        if much_tag_flag != 0:
            tagshowtext = tagshowtext+" +"+str(much_tag_flag)
        sys.stdout.write(templetes.format(
            pkg_name=i[0], tags=tagshowtext, description=i[2], author=i[4], repo=i[1])+"\n")
    if much_pkg_list != 0:
        sys.stdout.write(f"-- More {much_pkg_list} Package(s) --"+"\n")

    conn.close()
    lockn.remove()

    return pkg_list_clean
